Variables in C

In C language, variables are used to store some data in it that the programs can manipulate. It uses the computer's memory space.

When we want to store some values in our program, we store it in the memory space and name the memory space for easy access.

The name of a variable can be composed of letters, digits, and the underscore character. It should begin with either a letter or an underscore. It should not use any inbuilt keywords of C as the variable name.

The variable must be given a type, which defines what type of data the variable will hold.

Different data types are

  • int - To hold an integer value.

  • float - single-precision floating point value.

  • double - double-precision floating point value.

  • char - To store a character in it.

  • void - No available data type.

Declaration of a variable

Declaration tells the compiler about data type and size of the variable. In order to use any variable in a C program we need to declare the variable during the start of the program.

A variable is declared using the extern keyword, outside the main() function.

Example

extern int x;

Defining a variable

Definition a variable means the compiler will allocate memory to the variable.

Example

int x;

Initializing a variable

Initializing a variable is to provide a value to the variable. A variable can be initialized and defined in a single statement.

Example

int x = 5;

Lets see it with an example program

#include<stdio.h>

// Variable declaration(optional)
extern int x, y,result;

int main () {

    // variable definition
    int x, y, result;
 
    // actual initialization
    x = 12;
    y = 18;
	
    // Perform add operation
    result = x+y;
	
    // Print the result
    printf("Result is : %d", result);
    return 0;
}

Output

Result is 30

Most Read